<?php
namespace app\share\controller;

use app\reception\model\ThirdArgumentModel;
use app\common\ali_note\SendSms;
use app\common\ResponseFormat;
use think\Controller;


/**
 * Class Verification 所有的验证类
 * @package app\api\controller
 */
class Verification extends Controller {


    /**
     * @date 2019/8/19 13:49
     * @description 验证码检查
     * @param $phone
     * @param $phone_verification_code
     * @return array
     * @author cxh
     */
    public function verification_code_check($phone,$phone_verification_code){
        //校验验证码是否正确
        $session_verification = session('verification');
        if(empty($session_verification)||$session_verification['phone']!=$phone||$session_verification['phone_verification_code']!=$phone_verification_code){
            return ResponseFormat::failed_array(ResponseFormat::BUSINESS_LOGIC_RESTRICT,'验证码不正确');
        }
        if(time()>$session_verification['phone_verification_code_expiration_time']){
            return ResponseFormat::failed_array(ResponseFormat::BUSINESS_LOGIC_RESTRICT,'验证码超时，请重新获取');
        }

        session('verification','');//删除session中的验证码
        return ResponseFormat::success_array();

    }





    /**
     * @date 2019/8/19 9:33
     * @description 发送短信验证码
     * @author cxh
     * @return array
     */
    public function send_phone_verification_code(){
        $phone = input('param.phone');

        if(!is_phone($phone)){
            return ResponseFormat::failed_array(ResponseFormat::ILLEGAL_PARAMETER,'手机号码不正确');
        }

        //TODO:限制手机号发送次数
        $phone_verification_code = generate_code(); //生成短信验证码

        $phone_verification_code_expiration_time = time() + 60*5; //有效期为5分钟
        $data = [
            'phone'                                   => $phone,
            'phone_verification_code'                 => $phone_verification_code,
            'phone_verification_code_expiration_time' => $phone_verification_code_expiration_time,
        ];

        session('verification',$data); //设置到session中，如果没有session建议设置到缓存中

        $third_argument_model = new ThirdArgumentModel();
        $ali_note_config = $third_argument_model->get_ali_note_config_data(); //获取阿里大鱼短信配置 //改为直接从缓存中读取

        if(empty($ali_note_config)){
            return ResponseFormat::failed_array(ResponseFormat::BUSINESS_LOGIC_RESTRICT,'短信配置参数获取失败');
        }
        $send_sms = new SendSms($ali_note_config['ACCESS_KEY_ID'],$ali_note_config['ACCESS_KEY_SECRET'],$ali_note_config['TEMPLATE_CODE'],$ali_note_config['FREE_SIGN_NAME']);

        $send_result = $send_sms->send($phone,$phone_verification_code);
        $send_result = json_decode($send_result,true);
        if($send_result['Message'] === 'OK'){
            return ResponseFormat::success_array();
        }else{
            return ResponseFormat::failed_array(ResponseFormat::FAILED,'发送失败');
        }
    }



}